package com.xiaowen.tool.threadUtil;


import com.xiaowen.tool.threadUtil.ThreadExecutorManager.CustomRejectedExecutionHandler;
import com.xiaowen.tool.threadUtil.ThreadExecutorManager.SynThreadPoolExecutor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: yf-wenhao
 * Date: 17/8/11
 * Time: 上午9:45
 */
public class ThreadPoolExecutorFactory {

    /**
     * 线程池初始化方法
     *
     * corePoolSize 核心线程池大小----50
     * maximumPoolSize 最大线程池大小----100
     * keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间----10 分钟
     * TimeUnit keepAliveTime时间单位----TimeUnit.MINUTES
     * workQueue 阻塞队列----new ArrayBlockingQueue<Runnable>(10)====500容量的阻塞队列
     * threadFactory 新建线程工厂----new CustomThreadFactory()====定制的线程工厂
     * rejectedExecutionHandler 当提交任务数超过maximumPoolSize+workQueue之和时,
     *
     *                                任务会交给RejectedExecutionHandler来处理
     */
    //volatile防止 指令重排序导致的dcl问题
    private volatile static ThreadPoolExecutor threadPoolExecutor;

    private ThreadPoolExecutorFactory(){
    }

    //双重判断
    public static ThreadPoolExecutor getInstance(){
        if (null == threadPoolExecutor) {
            synchronized (ThreadPoolExecutorFactory.class) {
                if (null == threadPoolExecutor) {
                    threadPoolExecutor = new SynThreadPoolExecutor(
                            20,
                            200,
                            10,
                            TimeUnit.MINUTES,
                            new ArrayBlockingQueue<>(8000),
                            new ThreadFactory(),
                            new CustomRejectedExecutionHandler());
                }

            }
        }
        return threadPoolExecutor;
    }

}
